<template>
  <div>
    <el-dialog
      v-loading="isLoading"
      title="分配权限"
      :visible="isVisible"
      width="50%"
      @close="$emit('update:isVisible', false)"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item>
          <el-checkbox-group v-model="form.authList">
            <el-checkbox
              v-for="item in authArr"
              :key="item.id"
              value="item.id"
              :label="item.id"
            >{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:isVisible', false)">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAuthList } from '@/api/auth'
import { assignPrem, getRoleInfo } from '@/api/role'
export default {
  name: 'DistributionAuth',
  components: {},
  props: {
    isVisible: {
      type: Boolean,
      required: true
    },
    roleId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      authArr: [],
      isLoading: true,
      form: {
        authList: []
      }
    }
  },
  computed: {},
  watch: {
    isVisible(newVal, oldVal) {
      if (!newVal) return
      this.getRoleInfo()
    }
  },
  async created() {
    this.getAuthList()
  },
  mounted() {
  },
  methods: {
    async getAuthList() {
      this.isLoading = true
      const { data } = await getAuthList()
      console.log(data)
      this.authArr = data.filter(item => item.enVisible === '1')
      this.isLoading = false
    },
    async submit() {
      this.$emit('update:isVisible', false)
      // const arr = this.form.authList.map(name => this.authArr.find(obj => obj.name === name).id)
      // console.log(arr)
      this.isLoading = true
      await assignPrem({
        id: this.roleId,
        permIds: this.form.authList
      })
      // 提示
      this.isLoading = false
      this.$message.success('分配成功！')
    },
    async getRoleInfo() {
      this.isLoading = true
      const res = await getRoleInfo(this.roleId)
      console.log(res)
      this.form.authList = res.data.permIds
      this.isLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
